/**
 * Created by chengming on 18/4/18.
 * version 1.0
 */
const BaseAdapter = require('./base/BaseAdapter');
const logger = require('../conf/logger');
const request = require('request-promise');
const cheerio = require('cheerio');
const moment = require('moment');
const urlTool = require('url');
const server = require('../conf/server');
const iconv = require("iconv-lite");
const report = require('../exception/ErrorReport');

class ArticleUpdateDetailAdapter extends BaseAdapter{

	constructor(page, isTest, notTime){
		super(page, page.encoding ||'UTF-8', isTest, notTime);
		this.contentRule = page.contentRule;
		this.spiderIds = page.spiderIds;
		this.pageTitle = page.pageTitle;
		this.pageSite = page.pageSite;
	}

	async execute(){
		logger.debug('开始执行抓取');

        if(this.spiderIds || this.spiderIds.length == 0){

        	return {
        		code:559,
				errMsg: '没有指定spider id 无法更新'
			}
		}

		let body = await this.doRequest();

		let decodeBody = iconv.decode(body, this.encoding).toString();

		logger.debug('抓取执行完毕,开始分析文本');
		if(!this.contentRule || this.contentRule.length == 0){
			logger.warn('没有内容抓取规则');
			if(this.isTest == false){
				await report(this.sourceUrl, this.source, this.requestUrl,'没有内容抓取规则');
			}
			return {
				code: 411,
				errMsg:'没有内容抓取规则'
			}
		}

		let $ = cheerio.load(decodeBody);
		let content = $(this.contentRule).html();

		return await super.postUpdateSpider(this.pageTitle, content, this.pageSite, this.spiderIds);
	}
}

module.exports = ArticleUpdateDetailAdapter;